Why is argv[0] in C/C++ not a good idea to use
Daniel Nashed – 31 October 2023 09:18:50
argv[0] on Linux and Windows
Looking into the APIs for creating new processes shows that and application can specify any string as arg[0] when calling your process.
This leads to the conclusion that using argv[0] as a trustworthy information isn't a good idea.
I would even recommend not using it at all even for display purposes and would just skip argv[0] completely.
What would be a good way to determine the binary name?
On Linux the proc file system contains information about processes. It's by the way a very easy to use standardized way accessing process information.
There is even a special link "/proc/self" which represents the running process binary.
Using readlink ("/proc/self/exe"...) is a simple way to get the current binary name.
On Windows using GetModuleFileName (NULL, ...) is a good way to get the current binary name.
-- Daniel
Refrences
Linux:
https://man7.org/linux/man-pages/man3/exec.3.html
Example:
execl (szProgram, szProgram, szArg1, szArg2, NULL);
Windows:
https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa
Example:
bSuccess = CreateProcessAsUser(
NULL, // Application name
pszCommandLine,
NULL,
NULL,
FALSE,
NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
NULL,
pszWorkDir,
&StartupInfo,
&ProcessInfo);
- Comments [0]